package top.ahzy.seobench.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import top.ahzy.seobench.result.Result;

import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;

/**
 * @author ahzy
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理空指针的异常
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = NullPointerException.class)
    @ResponseBody
    public Result exceptionHandler(HttpServletResponse req, NullPointerException e){
        logger.error("发生空指针异常！原因是:",e);
        return Result.error( "发生空指针异常");
    }

    /**
     * 请求入参校验参数不能为空(json)
     * @param response
     * @param e
     * @return
     */
    @ExceptionHandler({BindException.class})
    @ResponseBody
    public Result exceptionHandler(HttpServletResponse response, BindException e){
        return Result.error(e.getBindingResult().getFieldErrors().get(0).getDefaultMessage());
    }

    /**
     * 请求入参校验参数不能为空(x-www-form-urlencoded)
     * @param response
     * @param e
     * @return
     */
    @ExceptionHandler({ConstraintViolationException.class})
    @ResponseBody
    public Result exceptionHandler(HttpServletResponse response, ConstraintViolationException e) {
        String message =null;
        for (ConstraintViolation violation : e.getConstraintViolations()) {
            message = violation.getMessageTemplate();
        }
        return Result.error(message);
    }

    /**
     * 请求入参校验集合不能为空  @NotEmpty
     * @param response
     * @param e
     * @return
     */
    @ExceptionHandler({MethodArgumentNotValidException.class})
    @ResponseBody
    public Result exceptionHandler(HttpServletResponse response, MethodArgumentNotValidException e) {
        return Result.error(e.getBindingResult().getFieldError().getDefaultMessage());
    }
    /**
     * 未登录异常
     * @param response
     * @param e
     * @return
     */
    @ExceptionHandler(value =NotLoginException.class)
    @ResponseBody
    public Result ootLoginException(HttpServletResponse response, NotLoginException e){
        logger.error("未知异常！原因是:",e);
        return Result.error(e.getMessage(),e.getCode());
    }




    /**
     * 处理其他异常
     * @param response
     * @param e
     * @return
     */
    @ExceptionHandler(value =Exception.class)
    @ResponseBody
    public Result exceptionHandler(HttpServletResponse response, Exception e){
        logger.error("未知异常！原因是:",e);
        return Result.error( "系统异常");
    }
}
